package com.lagou.rocketmq.consumer;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.lagou.constant.OrderStatusEnum;
import com.lagou.constant.RedisConstant;
import com.lagou.constant.RocketMQConstant;
import com.lagou.entity.TbOrder;
import com.lagou.service.TbOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @ClassName: CreateOrderConsumer
 * @Description: 创建订单消费者
 * @Author: qjc
 * @Date: 2021/12/21 3:33 下午
 */
@Component
@Slf4j
@RocketMQMessageListener(topic = RocketMQConstant.ORDER_TOPIC, consumerGroup = "${rocketmq.consumer.group}",
        messageModel = MessageModel.CLUSTERING, consumeMode = ConsumeMode.ORDERLY)
public class Consumer implements RocketMQListener<MessageExt> {

    @Autowired
    private TbOrderService orderService;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void onMessage(MessageExt messageExt) {
        String tags = messageExt.getTags();
        if (RocketMQConstant.CREATE_ORDER_TAG.equals(tags)) {
            long itemId = Long.parseLong(new String(messageExt.getBody()));
            orderService.saveOrder(itemId);
        } else if (RocketMQConstant.CANCEL_ORDER_TAG.equals(tags)) {
            long orderId = Long.parseLong(new String(messageExt.getBody()));
            TbOrder order = orderService.getById(orderId);
            if (ObjectUtils.isNotEmpty(order)) {
                Integer orderStatus = order.getStatus();
                if (OrderStatusEnum.WAIT_PAY.getCode().equals(orderStatus)) {
                    Long itemId = orderService.cancelOrder(orderId);
                    String itemStockKey = RedisConstant.ITEM_STOCK_KEY + ":" + itemId;
                    redisTemplate.opsForValue().increment(itemStockKey);
                } else if (OrderStatusEnum.PAID.getCode().equals(orderStatus)) {
                    log.info("订单：{}已支付", orderId);
                } else {
                    log.info("订单：{}已取消", orderId);
                }
            }
        } else {
            return;
        }

    }

}
